const Excel = require('exceljs')
const http = require('http')
// 一个参数是表头 第二个是表数据 第三个是那个字段是图片
const createExcel = async (columns, datalist, size) => {
  // 创建一个新的工作簿
  let workbook = new Excel.Workbook()
  // 添加一个工作表
  let worksheet = workbook.addWorksheet()

  // 添加表头
  worksheet.columns = columns
  datalist.forEach(async (item, index) => {
    worksheet.addRow(item)
  })
  if (size) {
    let picData = []
    datalist.forEach((item, rowIndex) => {
      return Object.keys(item).map((key, index) => {
        if (key !== size) {
          return item[key]
        }
        picData.push({
          col: index,
          row: rowIndex + 1,
          url: item[key],
        })
        return ''
      })
    })
    // 设置行高度
    for (let row = 1; row <= 5; row++) {
      worksheet.getRow(row).height = 30
    }
    // 设置表格的宽度和高度
    worksheet.getRow(1).eachCell((cell, colNumber) => {
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFFFFF00' }
      }
      cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } }
    })
    for (const row of picData) {
      const base64 = await imgUrlToBase64(row.url)
      const id = workbook.addImage({
        base64,
        extension: 'png',
      })
      worksheet.addImage(id, {
        // 指定在哪个单元格插入
        tl: { col: 0, row: row.row + 0.15 },
        // 指定图像大小
        ext: { width: 35, height: 35 },
      })
    }
  }
  //  写入文件
  const buffer = await workbook.xlsx.writeBuffer()
  return buffer
}
function imgUrlToBase64 (url) {
  let base64Img
  return new Promise((resolve) => {
    const req = http.get(url, (res) => {
      const chunks = []
      let size = 0
      res.on('data', (chunk) => {
        chunks.push(chunk)
        size += chunk.length
      })
      res.on('end', () => {
        const data = Buffer.concat(chunks, size)
        base64Img = data.toString('base64')
        resolve(base64Img)
      })
    })
    req.on('error', () => {
      resolve('')
    })
    req.end()
  })
}
module.exports = {
  createExcel
}